#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
import os
import logging
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util,template
from google.appengine.ext import db
from google.appengine.api import channel
from google.appengine.api import users


class Source(db.Model):
	user = db.UserProperty()
	code = db.TextProperty()
	fileName = db.StringProperty()

class MainHandler(webapp.RequestHandler):
    def get(self):
		user = users.get_current_user()

		if not user:
			self.redirect(users.create_login_url(self.request.uri))
		else:
			id = channel.create_channel(user.user_id())
			
			greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
                                (user.nickname(), users.create_logout_url("/")))
		
			code_query = Source.all()
			code_query.filter('user =', users.get_current_user())
			codes = code_query.fetch(100, 0)
			template_values = {
					'codes': codes,
					'greeting': greeting,
					'user': user,
					'channel_id': id
					}

			path = os.path.join(os.path.dirname(__file__), 'main.html')
			self.response.out.write(template.render(path, template_values))

	
class Save(webapp.RequestHandler):
	def post(self):
		message = simplejson.loads(self.request.body)
		source = Source()
		source.user = users.get_current_user()
		source.code = message['code']
		#source.code = message.code
		source.fileName = message['fileName']
		#source.fileName = message.fileName
		source.put()

		
# Modify Load class to take Codes via 'key' table and send them via channel to Main		
		
class Load(webapp.RequestHandler):
	def post(self):
		channel_id = users.get_current_user().user_id()
		message = simplejson.loads(self.request.get('message'))
		fileName = message['fileName']
		query = Source.all()
		query.filter('user =', users.get_current_user())
		query = db.GqlQuery("SELECT * FROM Source WHERE fileName = :1", fileName)
		query.fetch(1,0)
		thisCode = query[0]
		loadMessage = {
			'id' : "load",
			'code': thisCode.code
		}
		messageType = {
			'id': "load"
		}
		#logging.debug(thisCode.code)
		#logging.debug(channel_id)
		#channel.send_message(channel_id, simplejson.dumps(loadMessage))
		#channel.send_message(channel_id, messageType)
		logging.debug(loadMessage)
		self.response.out.write(simplejson.dumps(loadMessage))
		
class LoadList(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		query = Source.all()
		query.filter('user =', user)
		query = db.GqlQuery("SELECT * FROM Source")
		loadvalues = {
			"data" : query.fetch(100,0)
		}
		path = os.path.join(os.path.dirname(__file__), 'loadvalues.html')
		self.response.out.write(template.render(path, loadvalues))

class Download(webapp.RequestHandler):
	def get(self):
		#fileName = self.request.url()
		message = self.request.get('filename')
		fileName = message
		logging.debug("filename = " + fileName)
		query = Source.all()
		query.filter('user =', users.get_current_user())
		query = db.GqlQuery('SELECT * FROM Source WHERE fileName = :1', fileName)
		query.fetch(1,0)
		thisCode = query[0]
		downloadMessage = thisCode.code
		self.response.headers['Content-Disposition'] = "attachment; filename=%s" % fileName
		self.response.headers['Content-Type'] = "text/plain"
		self.response.out.write(downloadMessage)
		

def main():
	logging.getLogger().setLevel(logging.DEBUG)
	application = webapp.WSGIApplication([('/', MainHandler),
											('/load', Load),
										  ('/save', Save),
										  ('/loadvalues', LoadList),
										  ('/download', Download)],
                                         debug=True)
	util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
